package pl.kozulowski.components {
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class ScrollBar extends MovieClip {
		
		private var _handle:MovieClip;
		private var _track:MovieClip;
		private var _target:MovieClip;
		private var _targety:Number;
		private var _mask:MovieClip;;
		private var _scrollheight:Number;
		
		public function ScrollBar($track:MovieClip, $handle:MovieClip, $target:MovieClip, $mask:MovieClip) {
			_track = $track;
			_handle = $handle;
			_target = $target;
			_targety = _target.y;
			_mask = $mask;
			_target.mask = _mask;
			_scrollheight = _track.height - _handle.height;
			_handle.buttonMode = true;
			_handle.addEventListener(MouseEvent.MOUSE_DOWN, onGrab);
			_handle.addEventListener(MouseEvent.MOUSE_UP, onRel);
			_handle.stage.addEventListener(MouseEvent.MOUSE_UP, onRel);
		}
		
		private function onRel($e:MouseEvent):void {
			_handle.stopDrag();
		}
		
		private function onGrab($e:MouseEvent):void {
			_handle.startDrag(false, new Rectangle(_track.x+1, _track.y, 0, _track.height-_handle.height));
			addEventListener(Event.ENTER_FRAME, onFrame);
		}
		
		private function onFrame($e:Event):void {
			trace((_handle.y-_track.y)/_scrollheight);
			_target.y = -((_handle.y-_track.y)/_scrollheight)*(_target.height-_mask.height)+_targety;
		}
	}
}